#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define rep(i,a,b) for(register int i = (a);i <= (b);++i)
#define per(i,a,b) for(register int i = (a);i >= (b);--i)  
typedef long long ll;
typedef unsigned long long ull;
using std::string;using std::cin;using std::cout;

int _,len,ans,tmp;
char ch[200005];

inline int solve1(int x){
    int t = 0;
    rep(i,1,len) if(ch[i] - '0' == x) ++t;
    return t;
}

inline int solve2(int x,int y){
    int t = 0;
    int i = 1;
    while(i <= len){
        while(ch[i] - '0' != x && i <= len) ++i;
        if(ch[i] - '0' == x) ++t;
        while(ch[i] - '0' != y && i <= len) ++i;
        if(ch[i] - '0' == y) ++t;;
    }
    return t - t%2;
}

int main(){
    std::ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    //freopen("in.in", "r", stdin);
    cin >> _;
    while(_--){
        cin >> ch+1;
        len = strlen(ch+1);
        ans = len-2 , tmp = 1;
        rep(i,0,9) tmp = std::max(tmp,solve1(i));
        ans = std::min(ans,len - tmp);
        tmp = 2;
        // cout << ans << "\n";
        rep(i,0,9){
            rep(j,0,9){
                if(i == j) continue;
                tmp = std::max(tmp,solve2(i,j));
                ans = std::min(ans,len - tmp);
            }
        }
        cout << ans << "\n";
    }
    return 0;
}